const LBS_KEY = 'ADOBZ-6BLWU-DBTVF-GRL73-ZLRDO-KUBX3';
const baseUrl = 'https://gss.api.holyes.com/gss2.0';
import { createXsign } from '../tools/tools';
const DEFAULT_KEY = 'd303f040ab6fbaa0';

// Common Request
async function myRequest(url, method, data, h = {}) {
  const userInfo = uni.getStorageSync('userInfo') || {};
  let key = data?.key || userInfo.custAccountCode || DEFAULT_KEY;
  const CustAccountCode =
    data?.CustAccountCode || userInfo.custAccountCode || '99000002';
  let header = {
    Authorization: userInfo.token || '',
    CustAccountCode,
    ...h,
  };
  if (data?.key) {
    delete data.key;
  }
  const config = {
    method,
    params: method === 'GET' ? data : {},
    data: method === 'POST' ? data : {},
    key,
  };
  await createXsign(config);
  const queryStr = Object.keys(config.params)
    .map((k) => `${k}=${config.params[k]}`)
    .join('&');

  if (method === 'POST') {
    data = Object.keys(data)
      .map((k) => `${k}=${encodeURIComponent(data[k])}`)
      .join('&');
    header = { ...header, 'Content-Type': 'application/x-www-form-urlencoded' };
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: url + '?' + queryStr,
      method,
      data,
      header,
      success: (res) => {
        console.log(
          'Api',
          `MyRequest called url(${method}) -> ${url.replaceAll(
            baseUrl,
            '',
          )} req.data -> ${JSON.stringify(data)}`,
          res.data,
        );
        const { success, data, message } = res.data;
        if (success) {
          resolve(data);
        } else {
          uni.showToast({
            title: message || '请求失败',
            icon: 'none',
          });
          reject(message);
        }
      },
      fail: (res) => {
        reject(res);
      },
    });
  });
}

export const addressList = function () {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `https://apis.map.qq.com/ws/district/v1/list?key=${LBS_KEY}`,
      method: 'GET',
      success: (res) => {
        resolve(res.data);
      },
      fail: (res) => {
        reject(res);
      },
    });
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/ValidVersion
/**
 * 检查当前门店系统版本
 * @returns
 */
export const ValidVersion = function () {
  return myRequest(`${baseUrl}/Mini/Customer/ValidVersion`, 'GET', {
    CustAccountCode: '99000002',
    key: DEFAULT_KEY,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/GetWxSessionKey
/**
 * 登录凭证Code交换OpenId
 * @param {*} Code 小程序接口wx.login 返回的Code
 * @returns
 */
export const GetWxSessionKey = function (Code) {
  return myRequest(`${baseUrl}/Mini/Customer/GetWxSessionKey`, 'GET', {
    Code,
    CustAccountCode: '99000002',
    key: DEFAULT_KEY,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Store/GetStoreByUserLocation
/**
 * 获取附近门店
 * @param {*} Longitude
 * @param {*} Latitude
 * @returns
 */
export const GetStoreByUserLocation = function (Longitude, Latitude) {
  return myRequest(`${baseUrl}/Mini/Store/GetStoreByUserLocation`, 'GET', {
    Longitude,
    Latitude,
    CustAccountCode: '99000002',
    key: DEFAULT_KEY,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Reg
/**
 * 注册
 * @param {*} OpenId 小程序OpenID
 * @param {*} Mobile 手机
 * @param {*} Name
 * @param {*} Addr
 * @param {*} Birthday
 * @param {*} Sex
 * @param {*} HeadPortrait 头像base64
 * @param {*} WxOpenId 公众号OpenId
 * @param {*} ParentId 家庭成员》新增成员时传值(登录时返回)，正常传空
 * @param {*} Referrer 推荐人ID
 * @returns
 */
export const Reg = function (
  OpenId,
  Mobile,
  Name,
  Addr,
  Birthday,
  Sex,
  HeadPortrait,
  ReadMe,
  WxOpenId,
  ParentId,
  Referrer,
) {
  const data = {
    OpenId,
    Mobile,
    Name,
    Addr,
    Birthday,
    Sex,
    CustAccountCode: '99000002',
    key: DEFAULT_KEY,
  };
  if (HeadPortrait) {
    data.HeadPortrait = HeadPortrait;
  }
  if (ReadMe) {
    data.ReadMe = ReadMe;
  }
  if (WxOpenId) {
    data.WxOpenId = WxOpenId;
  }
  if (ParentId) {
    data.ParentId = ParentId;
  }
  if (Referrer) {
    data.Referrer = Referrer;
  }
  return myRequest(`${baseUrl}/Mini/Customer/Reg`, 'POST', data);
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Login
/**
 * 顾客登录接口
 * @param {*} OpenId 小程序OpenId
 * @param {*} Mobile 顾客手机号码
 * @param {*} WxOpenId 公众号OpenId
 * @param {*} SelectCustomerId 指定要复制的顾客ID（顾客已经登录的情况下，切换门店，带上这个参数）
 * @param {*} SmsCode 短信验证码(可选)
 * @returns
 */
export const Login = function (
  OpenId,
  Mobile,
  WxOpenId = '',
  SelectCustomerId = '',
  SmsCode = '',
) {
  const data = {
    OpenId,
    Mobile,
    WxOpenId,
    SelectCustomerId,
    CustAccountCode: '99000002',
    key: DEFAULT_KEY,
  };
  if (SmsCode) {
    data.SmsCode = SmsCode;
  }
  return myRequest(`${baseUrl}/Mini/Customer/Login`, 'POST', data);
};
// https://gss.api.holyes.com/gss2.0/common/gssWechat/gssGetUserMobileInfo
/**
 * 顾客获取手机号码
 * @param {*} AppId 小程序AppId
 * @param {*} Code 小程序接口getPhoneNumber返回的Code
 */
export const GssGetUserMobileInfo = function (AppId, Code) {
  return myRequest(`${baseUrl}/common/gssWechat/gssGetUserMobileInfo`, 'GET', {
    AppId,
    Code,
    CustAccountCode: '99000002',
    key: DEFAULT_KEY,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Store/GetDictionaryByType
/**
 * 获取门店预约的项目及描述
 * @param {*} CustAccountCode 示例值:门店代号
 * @param {*} DictionaryType 示例值:Reservation
 * @returns
 */
export const GetDictionaryByType = function (
  CustAccountCode,
  DictionaryType = 'Reservation',
) {
  return myRequest(`${baseUrl}/Mini/Store/GetDictionaryByType`, 'GET', {
    DictionaryType,
    CustAccountCode,
    key: DEFAULT_KEY,
  });
};
// https://gss.api.holyes.com/gss2.0/common/gssWechat/gssGetScene
/**
 * 根据扫码场景值，获取具体参数
 * @param {*} SceneMapId 场景值
 * @returns
 */
export const GssGetScene = function (SceneMapId) {
  return myRequest(`${baseUrl}/common/gssWechat/gssGetScene`, 'GET', {
    SceneMapId,
    CustAccountCode: '99000002',
    key: DEFAULT_KEY,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/CheckMpCode
/**
 * 检查是否从配置公众号进入的小程序
 * @param {*} CheckCode 门店代号
 * @returns
 */
export const CheckMpCode = function (CheckCode) {
  return myRequest(`${baseUrl}/Mini/Customer/CheckMpCode`, 'GET', {
    CheckCode,
    CustAccountCode: '99000002',
    key: DEFAULT_KEY,
  });
};
// https://gss.api.holyes.com/gss2.0/Common/gssWechat/gssGetQrCodev3
/**
 * 获取带参二维码
 * @param {*} PagePath 页面地址:如果要跳转详情，就填写详情的地址 示例值:pages/startPage/startPage
 * @param {*} SceneMap 参数：例如优惠券代号，赠送人ID等，可以是JSON字符串等，这里传入之后，扫码后调用接口：【根据扫码场景值，获取具体参数】
 * @returns
 */
export const GssGetQrCodev3 = function (PagePath, SceneMap) {
  const miniProgram = uni.getAccountInfoSync().miniProgram;
  const AppId = miniProgram.appId;
  const envVersion = miniProgram.envVersion;
  return myRequest(`${baseUrl}/Common/gssWechat/gssGetQrCodev3`, 'GET', {
    AppId,
    PagePath,
    SceneMap,
    CustAccountCode: '99000002',
    Check_path: false,
    Env_version: envVersion,
    key: DEFAULT_KEY,
  });
};
// https://gss.api.holyes.com/gss2.0/common/file/GetImage
/**
 * 获取指定宽高的图片
 * @param {*} path
 * @returns
 */
export const BuildImageUrl = function (path, w = 0, h = 0) {
  return (
    `${baseUrl}/common/file/GetImage` + `?x-version=1.0&path=${path}_${w}x${h}`
  );
};
// https://gss.api.holyes.com/gss2.0/Common/GssSms/SendGssMsg
/**
 * 发送验证码
 * @param Mobile 手机号
 * @returns {Promise<unknown>}
 * @constructor
 */
export const SendGssMsg = function (Mobile) {
  return myRequest(`${baseUrl}/Common/GssSms/SendGssMsg`, 'POST', {
    Mobile,
    MsgType: '验证码登录',
    CustAccountCode: '99000002',
    key: DEFAULT_KEY,
  });
};

// ------------------- 登录后的接口 -------------------

// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 新增接待记录
 * @param {*} StoreClerkId 店员ID，店员扫码时带的参数
 * @returns
 */
export const CustomerQuery = function (StoreClerkId) {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'POST', {
    StoreClerkId,
    CustomerId: '',
    OpenId: '',
    Action: 'Holyes_ReceptionRecord_Add',
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 获取会员支付码
 * @returns
 */
export const GetCustomerAccountCode = function () {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'GET', {
    Action: 'Holyes_PayMentAccount_Get',
    Customerid: '',
    Custaccountcode: '',
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 获取余额列表
 * @param {*} OptionType 全部/储值记录/消费记录
 * @param {*} Page 页码
 * @param {*} Limit 每页条数
 * @returns
 */
export const GetCustomerOrder = function (
  OptionType = '全部',
  Page = '1',
  Limit = '20',
) {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'GET', {
    OptionType,
    Action: 'Holyes_CustomerOrder_GetLog',
    Customerid: '',
    CustAccountCode: '',
    Type: 0,
    Page,
    Limit,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/GetAppointmentList
/**
 * 获取预约记录
 * @returns
 */
export const GetAppointmentList = function (Longitude, Latitude) {
  return myRequest(`${baseUrl}/Mini/Customer/GetAppointmentList`, 'GET', {
    Longitude,
    Latitude,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/AppointmentListCancel
/**
 * 取消预约
 * @param {*} RecId 预约记录ID
 * @returns
 */
export const AppointmentListCancel = function (RecId) {
  return myRequest(`${baseUrl}/Mini/Customer/AppointmentListCancel`, 'POST', {
    RecId,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/GetAppointmentTime
/**
 * 获取预约配置
 * @param {*} CustAccountCode 要预约的门店
 */
export const GetAppointmentTime = function (CustAccountCode) {
  return myRequest(`${baseUrl}/Mini/Customer/GetAppointmentTime`, 'GET', {
    CustAccountCode,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/GetRelationClerkList
/**
 * 获取绑定导购员列表
 * @param {*} CustAccountCode 当前操作门店
 * @returns
 */
export const GetRelationClerkList = function (CustAccountCode) {
  return myRequest(`${baseUrl}/Mini/Customer/GetRelationClerkList`, 'GET', {
    CustAccountCode,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/AppointmentListAdd
/**
 * 新增预约记录
 * @param {*} AppointmentTime 时间段 示例值:14：00-16：00
 * @param {*} ItemName 预约项 示例值:配镜
 * @param {*} AppointmentDate 预约日期 示例值:2024-06-12
 * @param {*} ExpectedNumber 到店人数 示例值:1
 * @param {*} SortNumber 时间段的序号，第几个时间段 示例值:1
 * @param {*} Remark 备注 示例值:备注
 * @param {*} GuideClerkId 导购员ID 示例值:导购员ID
 * @param {*} CustAccountCode 门店代号 示例值:门店代号
 * @returns
 */
export const AppointmentListAdd = function (
  AppointmentTime,
  ItemName,
  AppointmentDate,
  ExpectedNumber,
  SortNumber,
  Remark,
  GuideClerkId,
  CustAccountCode,
) {
  return myRequest(`${baseUrl}/Mini/Customer/AppointmentListAdd`, 'POST', {
    AppointmentTime,
    ItemName,
    AppointmentDate,
    ExpectedNumber,
    SortNumber,
    Remark,
    GuideClerkId,
    CustAccountCode,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 获取子账号列表
 * @returns
 */
export const CustomerGetChilds = function () {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'GET', {
    Action: 'Holyes_Customer_GetChilds',
    CustomerId: '',
    CustAccountCode: '',
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/SwichAccount
/**
 * 切换子账号
 * @param {*} Mobile 子账号手机号
 * @param {*} CustomerId 子账号ID，接口【获取子账号列表】返回
 * @returns
 */
export const SwichAccount = function (Mobile, CustomerId) {
  return myRequest(`${baseUrl}/Mini/Customer/SwichAccount`, 'POST', {
    CustomerId,
    Mobile,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/UpdateCustomerInfo
/**
 * 修改资料
 * @param {*} Name
 * @param {*} Addr 示例值: 广东省深圳市龙岗区坂田街道岗头新围仔
 * @param {*} Birthday 示例值: 1997-01-17
 * @param {*} Sex 示例值: 女
 * @param {*} HeadPortrait 示例值: 头像Base64
 * @returns
 */
export const UpdateCustomerInfo = function (
  Name,
  Addr,
  Birthday,
  Sex,
  HeadPortrait,
) {
  const data = {};
  if (Name) {
    data.Name = Name;
  }
  if (Addr) {
    data.Addr = Addr;
  }
  if (Birthday) {
    data.Birthday = Birthday;
  }
  if (Sex) {
    data.Sex = Sex;
  }
  if (HeadPortrait) {
    data.HeadPortrait = HeadPortrait;
  }
  return myRequest(`${baseUrl}/Mini/Customer/UpdateCustomerInfo`, 'POST', data);
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 获取优惠券列表
 * @returns
 */
export const GetMyCoupon = function () {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'GET', {
    Action: 'Holyes_MallCoupon_GetMyCoupon',
    Customerid: '',
    Custaccountcode: '',
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/GetDetail
/**
 * 优惠券详情
 * @param {*} CouponNumber 优惠券号
 * @returns
 */
export const GetCouponDetail = function (CouponNumber) {
  return myRequest(`${baseUrl}/Mini/Customer/GetDetail`, 'GET', {
    CouponNumber,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 顾客赠送优惠券给好友
 * @param {*} CouponNumber 优惠券ID
 * @param {*} GiftedCustomerId 受赠方顾客ID
 * @returns
 */
export const GiveCoupon = function (CouponNumber, GiftedCustomerId) {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'POST', {
    Action: 'Holyes_MallCoupon_Gift',
    CouponNumber,
    GiftedCustomerId,
    CustomerId: '',
    CustAccountCode: '',
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/GetCustomerAllOptometry
/**
 * 获取顾客验光单
 * @returns
 */
export const GetCustomerAllOptometry = function (token) {
  return myRequest(
    `${baseUrl}/Mini/Customer/GetCustomerAllOptometry`,
    'GET',
    {},
    token ? { Authorization: token } : {},
  );
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 获取顾客验光单曲线图
 * @returns
 */
export const GetCustomerAllOptometryLineData = function (token) {
  return myRequest(
    `${baseUrl}/Mini/Customer/Query`,
    'GET',
    {
      Action: 'Holyes_Customer_GetCusOptometryReport',
      CustomerId: '',
    },
    token ? { Authorization: token } : {},
  );
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/GetCustomerAllOrder
/**
 * 获取顾客所有订单
 * @returns
 */
export const GetCustomerAllOrder = function () {
  return myRequest(`${baseUrl}/Mini/Customer/GetCustomerAllOrder`, 'GET', {});
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 获取次卡列表
 * @returns
 */
export const GetCountCardList = function () {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'GET', {
    Action: 'Holyes_Customer_GetCountCardList',
    CustomerId: '',
    CustAccountCode: '',
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 获取资料
 * @returns
 */
export const GetUserInfo = function () {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'GET', {
    Action: 'Holyes_Customer_GetInfoByMini',
    Customerid: '',
    Custaccountcode: '',
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 获取推荐列表
 * @returns
 */
export const GetRecommendList = function () {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'GET', {
    Action: 'Holyes_Customer_GetReferrerList',
    customerId: '',
    custAccountCode: '',
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 助力优惠券(邀请他人进行助力)
 * @param {*} CouponNumber 优惠券号
 * @param {*} OpenId 助力人的小程序OpenId
 * @param {*} NickName 助力人微信昵称
 */
export const AssistCoupon = function (CouponNumber, OpenId, NickName) {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'POST', {
    Action: 'Holyes_MallCoupon_AssistanceRecord',
    CouponNumber,
    OpenId,
    NickName,
  });
};
// https://gss.api.holyes.com/gss2.0/Mini/Customer/Query
/**
 * 获取积分列表
 * @param {*} Page 页码
 * @param {*} Limit 每页条数
 * @returns
 */
export const GetCustomerIntegralList = function (Page = '1', Limit = '10') {
  return myRequest(`${baseUrl}/Mini/Customer/Query`, 'GET', {
    Action: 'Holyes_CustomerOrder_GetLog',
    CustomerId: '',
    CustAccountCode: '',
    Type: 1,
    Page,
    Limit,
  });
};
